<template>
  <div class="app-container">

    <!--新增按钮-->
    <el-row>
      <el-col :span="24">
        <div class="filter-container">
          <el-input placeholder="输入订单号或用户ID搜索" v-model="listQuery.query" style="width: 200px;" class="filter-item"
                    @keyup.enter.native="handleFilter"/>

          <el-select v-model="listQuery.orderStatus" placeholder="订单状态" clearable class="filter-item"
                     style="width: 150px" @change="handleFilter">
            <el-option v-for="{code, name} in orderStatusOptions" :key="code" :label="name"
                       :value="code"/>
          </el-select>

          <el-select v-model="listQuery.orgCode" placeholder="所属商家" clearable class="filter-item" :disabled="isOrg"
                     style="width: 150px" @change="handleFilter">
            <el-option v-for="{orgCode, orgName} in orgs" :key="orgCode" :label="orgName"
                       :value="orgCode"/>
          </el-select>

          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索
          </el-button>

          <el-checkbox v-model="showId" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+2">
            显示更多信息
          </el-checkbox>
        </div>
      </el-col>
    </el-row>

    <!--表格主体-->
    <el-row>
      <el-col :span="24">
        <el-table
          v-loading="listLoading"
          :height="tableHeight"
          :key="tableKey"
          :data="list"
          element-loading-text="Loading"
          border
          fit
          style="width: 100%;"
          highlight-current-row>
          <el-table-column align="center" label="序号" width="100px">
            <template slot-scope="scope">
              {{ scope.$index }}
            </template>
          </el-table-column>

          <el-table-column v-if="showId" label="订单ID" style="width: 20%" align="center">
            <template slot-scope="scope">
              <span style="color:#008842;">{{ scope.row.orderId }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="showId" label="用户ID" style="width: 20%" align="center">
            <template slot-scope="scope">
              <span style="color:#008842;">{{ scope.row.userId }}</span>
            </template>
          </el-table-column>

          <el-table-column label="订单金额" style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.payFee }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="下单时间" style="width: 10%" show-overflow-tooltip>
            <template slot-scope="scope">
              <i class="el-icon-time"/>
              <span>{{ scope.row.buyTime | timeFilter}}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注信息" style="width: 10%" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.remark }}
            </template>
          </el-table-column>
          <el-table-column class-name="status-col" label="订单状态" style="width: 10%" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.orderStatus | statusFilter">{{ scope.row.orderStatus |
                statusValueFilter(orderStatusOptions)}}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="success" @click="handleUpdate(scope.row)">
                详情
              </el-button>
              <el-button size="mini" type="info" @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <pagination v-show="total>0" :total="total"
                :page.sync="listQuery.pageNum"
                :limit.sync="listQuery.pageSize"
                layout="total, sizes, prev, pager, next"
                style="float:right;"
                @pagination="fetchData"/>

    <!--编辑弹窗-->
    <el-dialog :visible.sync="dialogFormVisible">

      <el-form ref="dataForm" :model="temp" label-position="right">

        <el-row :gutter="20" style="width: 90%;margin:0 auto">
          <el-col :span="8">
            <el-tag type="success" :offset="2">商品件数：{{temp.orderNum}}</el-tag>
          </el-col>
          <el-col :span="8">
            <el-tag type="danger">订单总值：{{temp.pageFee}}元</el-tag>
          </el-col>
          <el-col :span="8">
            <el-tag type="info">订单状态：{{temp.orderStatusName}}</el-tag>
          </el-col>
        </el-row>

        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="12">
            <el-form-item label="省市区：" label-width="105px" prop="areaName">
              <el-input v-model="temp.areaName" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址：" label-width="105px" prop="receiveAddress">
              <el-input v-model="temp.receiveAddress" disabled/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮政编码：" label-width="105px" prop="areaCode">
              <el-input v-model="temp.areaCode" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注信息：" label-width="105px" prop="remark">
              <el-input v-model="temp.remark" disabled/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" style="width: 80%;margin:0 auto">

          <el-collapse v-model="activeName" accordion>
            <el-collapse-item title="商品详情清单" name="1">
              <el-table
                :data="detailData"
                style="width: 100%">
                <el-table-column
                  prop="productName"
                  label="商品名称"
                  width="180">
                </el-table-column>
                <el-table-column
                  prop="price"
                  label="商品单价"
                  width="180">
                </el-table-column>
                <el-table-column
                  prop="productNum"
                  label="商品数量">
                </el-table-column>
              </el-table>
            </el-collapse-item>
          </el-collapse>
        </el-row>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sendOrder" :disabled="temp.orderStatus !== '1'">确认发货</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>

    </el-dialog>

  </div>
</template>

<script>

  import {
    getOrder,
    getListOrder,
    getPageOrder,
    updateOrder,
    createOrder,
    deleteOrder,
    getDetailListOrder,
    sendOrder,
    getAddress
  } from '@/api/manage/syOrder' //订单api层
  import SyOrgDictApi from '@/api/manage/syOrgDict';
  import waves from '@/directive/waves' //水波效果
  import Pagination from '@/components/Pagination' //分页插件
  import _ from 'lodash'

  export default {
    directives: {waves},
    components: {Pagination},
    filters: {
      /**
       * 状态颜色
       */
      statusFilter(status) {
        const statusMap = {
          1: 'warning',
          2: 'info',
          3: 'success',
          4: 'danger'
        }
        return statusMap[status]
      },
      /**
       * 状态名称
       */
      statusValueFilter(status, orderStatusOptions) {
        let statusObj = _.find(orderStatusOptions, {code: status});
        return statusObj ? statusObj.name : '';
      },
      /**
       * 时间过滤器
       */
      timeFilter(time) {
        if (time) {
          return new Date(time).Format('yyyy-MM-dd hh:mm:ss')
        } else {
          return ''
        }
      }
    },
    data() {
      return {
        orgCode: '',
        isOrg: false,
        tableHeight: window.innerHeight - 220, //表格高度
        activeName: 1,
        total: 0, // 分页总数
        tableKey: 0, //表格key
        list: null, //表格对象
        listLoading: true, //表格加载框
        listQuery: { //表格查询对象
          orderStatus: '',
          pageNum: 1,
          pageSize: 5,
          query: '',
          orgCode:''
        },
        orgs: [], //商家数据
        showId: false, //是否展示ID
        temp: {}, //编辑框临时变量
        dialogFormVisible: false, //编辑框显示
        detailData: [],//细表数据
        orderStatusOptions: [  //订单状态数据
          {'code': '', 'name': '全部'},
          {'code': '1', 'name': '待付款'},
          {'code': '2', 'name': '待发货'},
          {'code': '3', 'name': '已完成'},
          {'code': '4', 'name': '退款'}
        ],
        statusOptions: { //有效无效下拉框
          '1': '有效',
          '0': '作废'
        }
      }
    },
    computed: {},
    /**
     *初始化生命周期
     */
    created() {
      if(this.$store.getters.roles.indexOf('common') !== -1){
        this.orgCode = this.$store.getters.name;
        this.isOrg = true
        this.listQuery.orgCode = this.$store.getters.name;
      }
      this.fetchData()
    },
    methods: {
      /**
       * 表格数据加载
       */
      fetchData() {
        let that = this;
        this.listLoading = true
        this.$http.all([getPageOrder(this.listQuery), SyOrgDictApi.getList({validFlag: '1'})])
          .then(this.$http.spread(function (perms, orgs) {
            if(that.orgCode){
              that.orgs = orgs.filter(item => item.orgCode === that.orgCode)
            }else{
              that.orgs = orgs
            }
            that.list = perms.rows
            that.total = perms.total
            that.listLoading = false
          }));
      },
      /**
       * 编辑弹窗
       */
      handleUpdate(row) {
        let that = this;
        this.listLoading = true
        this.$http.all([getDetailListOrder({orderId: row.orderId}), getAddress({addressId: row.addressId})])
          .then(this.$http.spread(function (detail, address) {
            that.detailData = detail
            that.temp = Object.assign({}, address, row)
            let statusObj = _.find(that.orderStatusOptions, {code: row.orderStatus});
            that.temp.orderStatusName = statusObj ? statusObj.name : '';
            that.listLoading = false
            that.dialogFormVisible = true
          }));
      },
      /**
       * 确认发货
       */
      sendOrder() {
        let that = this;
        const tempData = Object.assign({}, this.temp)
        sendOrder(tempData).then(() => {
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '更新成功',
            type: 'success',
            duration: 1000,
            onClose() {
              that.fetchData();
            }
          })
        })
      },
      /**
       * 删除操作
       */
      handleDelete(row) {
        let that = this;
        deleteOrder({orderId: row.orderId}).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 1000,
            onClose() {
              that.fetchData();
            }
          })
        })
      },
      /**
       * 搜索过滤
       */
      handleFilter() {
        this.listQuery.page = 1
        this.fetchData()
      },
    }
  }
</script>

<style>
</style>
